<?php
class AuditTrailExtension extends DataExtension {
	function onAfterWrite(){
		if($this->owner->exists()){
			$data = $this->owner->getChangedFields(false, 1);
			if(sizeof($data)){
				$version = AuditTrail::get()->filter('ObjectClass', $this->owner->class)->filter('RowID', $this->owner->ID)->count() + 1;

				$audit_trail = Object::create('AuditTrail');
				$audit_trail->setField('ObjectClass', $this->owner->class);
				$audit_trail->setField('Version', $version);
				$audit_trail->setField('RowID', $this->owner->ID);
				$audit_trail->setField('IPAddress', $_SERVER['REMOTE_ADDR']);
				$audit_trail->setField('MemberID', Member::currentUserID());
				$audit_trail->write();

                $before_data = array();
                $after_data = array();
				foreach($data as $field_name => $value){
				    $before_data[$field_name] = $value['before'];
                    $after_data[$field_name] = $value['after'];
				}
                
                $audit_trail_detail = Object::create('AuditTrailDetail');
                $audit_trail_detail->setField('OldValue', AuditTrailDetail::EncodeData($before_data));
                $audit_trail_detail->setField('NewValue', AuditTrailDetail::EncodeData($after_data));
                $audit_trail_detail->setField('AuditTrailID', $audit_trail->ID);
                $audit_trail_detail->write();
			}
		}
	}
}

?>